<script setup lang='ts'>
import { marked } from 'marked'

const message = ref('')
const model = ref(['sonar-medium-online'])
const columns = [
  { text: 'mistral-7b-instruct', value: 'mistral-7b-instruct' },
  { text: 'mixtral-8x7b-instruct', value: 'mixtral-8x7b-instruct' },
  { text: 'sonar-small-chat', value: 'sonar-small-chat' },
  { text: 'sonar-medium-chat', value: 'sonar-medium-chat' },
  { text: 'sonar-small-online', value: 'sonar-small-online' },
  { text: 'sonar-medium-online', value: 'sonar-medium-online' },
  { text: 'codellama-70b-instruct', value: 'codellama-70b-instruct' },
]

const loading = ref(false)
const aiResponse = ref()
function startAI() {
  loading.value = true
  const options = {
    method: 'POST',
    headers: {
      'accept': 'application/json',
      'content-type': 'application/json',
      'authorization': 'Bearer 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'
    },
    body: JSON.stringify({
      model: model.value[0],
      messages: [
        { role: 'system', content: 'Be precise and concise.' },
        { role: 'user', content: message.value },
      ],
    }),
  }

  fetch('https://api.perplexity.ai/chat/completions', options)
    .then(response => response.json())
    .then((response) => {
      loading.value = false
      aiResponse.value = marked.parse(response.choices[0].message.content)
    })
    .catch((err) => {
      loading.value = false
      console.error(err)
    })
}
</script>

<template>
  <div>
    <van-picker v-model="model" title="模型" :columns="columns" :visible-option-num="3" :show-toolbar="true"
      confirm-button-text="" cancel-button-text="" />
    <van-field v-model="message" rows="3" autosize label="开始问吧" type="textarea" placeholder="请输入" show-word-limit />

    <van-button class="!mx-auto !mt-20px !w-70%" size="large" :loading="loading" type="primary"
      loading-text="Loading..." block @click="startAI">
      START
    </van-button>

    <div class="content m-20px border-1 border-#f4c291 b-rd-12px bg-#fff p-12px text-12px text-#000 leading-20px md:text-16px"
      v-html="aiResponse"></div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.content) {
  pre {
    border-radius: 8px;
    background-color: #111 !important;
    color: #fff;
    padding: 10px;
  }

  code {
    font-family: monospace;
  }
}
</style>
